import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Table,
  Tag,
  Space,
  Button,
  Typography,
  Spin,
  Empty
} from 'antd';
import {
  ReloadOutlined,
  BranchesOutlined,
  MenuOutlined,
  SettingOutlined,
  EyeOutlined,
  BarChartOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useTheme } from '../contexts/ThemeContext';
import { showNotification } from '../utils/notification';
import api from '../services/api';

const { Title, Text } = Typography;

interface RouteStatisticsData {
  total_routes: number;
  active_routes: number;
  inactive_routes: number;
  menu_routes: number;
  system_routes: number;
  custom_routes: number;
  permission_associations: number;
  level_distribution: Record<string, number>;
  statistics_time: string;
}

const RouteStatistics: React.FC = () => {
  const { currentTheme } = useTheme();
  const [loading, setLoading] = useState(false);
  const [statistics, setStatistics] = useState<RouteStatisticsData | null>(null);

  /**
   * 获取路由统计数据
   */
  const fetchStatistics = async () => {
    setLoading(true);
    try {
      const response = await api.get('/v1/routes/statistics');
      setStatistics(response.data.data);
    } catch (error: any) {
      console.error('获取路由统计失败:', error);
      showNotification('error', '获取统计数据失败', error.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatistics();
  }, []);

  if (loading && !statistics) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>
            <Text type="secondary">正在加载统计数据...</Text>
          </div>
        </div>
      </Card>
    );
  }

  if (!statistics) {
    return (
      <Card>
        <Empty description="暂无统计数据" />
      </Card>
    );
  }

  // 计算百分比
  const activePercentage = statistics.total_routes > 0 
    ? Math.round((statistics.active_routes / statistics.total_routes) * 100) 
    : 0;
  
  const menuPercentage = statistics.active_routes > 0 
    ? Math.round((statistics.menu_routes / statistics.active_routes) * 100) 
    : 0;

  const customPercentage = statistics.total_routes > 0 
    ? Math.round((statistics.custom_routes / statistics.total_routes) * 100) 
    : 0;

  // 层级分布数据
  const levelData = Object.entries(statistics.level_distribution).map(([level, count]) => ({
    level: level.replace('level_', '第') + '级',
    count,
    percentage: statistics.total_routes > 0 ? Math.round((count / statistics.total_routes) * 100) : 0
  }));

  const levelColumns: ColumnsType<any> = [
    {
      title: '路由层级',
      dataIndex: 'level',
      key: 'level',
    },
    {
      title: '数量',
      dataIndex: 'count',
      key: 'count',
      align: 'center',
    },
    {
      title: '占比',
      key: 'percentage',
      align: 'center',
      render: (_, record) => (
        <Tag color="blue">{record.percentage}%</Tag>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 24 }}>
          <div style={{ 
            display: 'flex', 
            justifyContent: 'space-between', 
            alignItems: 'center' 
          }}>
            <Title level={4} style={{ margin: 0 }}>
              <BarChartOutlined style={{ marginRight: 8 }} />
              路由统计概览
            </Title>
            <Button
              icon={<ReloadOutlined />}
              onClick={fetchStatistics}
              loading={loading}
            >
              刷新数据
            </Button>
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            统计时间: {new Date(statistics.statistics_time).toLocaleString()}
          </Text>
        </div>

        {/* 基础统计 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={12} md={6}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="路由总数"
                value={statistics.total_routes}
                prefix={<BranchesOutlined />}
                valueStyle={{ color: currentTheme.colorPrimary }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="活跃路由"
                value={statistics.active_routes}
                prefix={<EyeOutlined />}
                valueStyle={{ color: '#52c41a' }}
                suffix={
                  <div style={{ fontSize: '12px', color: currentTheme.colorTextSecondary }}>
                    ({activePercentage}%)
                  </div>
                }
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="菜单路由"
                value={statistics.menu_routes}
                prefix={<MenuOutlined />}
                valueStyle={{ color: '#1890ff' }}
                suffix={
                  <div style={{ fontSize: '12px', color: currentTheme.colorTextSecondary }}>
                    ({menuPercentage}%)
                  </div>
                }
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="权限关联"
                value={statistics.permission_associations}
                prefix={<SettingOutlined />}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 详细分析 */}
        <Row gutter={[16, 16]}>
          <Col xs={24} md={12}>
            <Card size="small" title="路由状态分布">
              <div style={{ marginBottom: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                  <Text>活跃路由</Text>
                  <Text strong>{statistics.active_routes}</Text>
                </div>
                <Progress 
                  percent={activePercentage} 
                  strokeColor="#52c41a"
                  size="small"
                />
              </div>
              
              <div style={{ marginBottom: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                  <Text>自定义路由</Text>
                  <Text strong>{statistics.custom_routes}</Text>
                </div>
                <Progress 
                  percent={customPercentage} 
                  strokeColor="#1890ff"
                  size="small"
                />
              </div>

              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                  <Text>系统路由</Text>
                  <Text strong>{statistics.system_routes}</Text>
                </div>
                <Progress 
                  percent={100 - customPercentage} 
                  strokeColor="#fa8c16"
                  size="small"
                />
              </div>
            </Card>
          </Col>

          <Col xs={24} md={12}>
            <Card size="small" title="层级分布">
              <Table
                columns={levelColumns}
                dataSource={levelData}
                pagination={false}
                size="small"
                rowKey="level"
              />
            </Card>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default RouteStatistics;
